package com.horizon.common.entity;

import com.horizon.common.util.IDGenerator;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

/**
 * 通用实体类，继承该类可获取主键、审计字段
 *
 * @author wangfuwei
 * @version 2018-08-07
 */
@Getter
@Setter
@MappedSuperclass
public abstract class BaseEntity implements IBaseEntity {

    /**
     * 主键
     */
    @Column(name = "fd_id", length = 32)
    @Id
    protected String fdId = IDGenerator.generateID();

    /**
     * 创建时间
     */
    @Setter(AccessLevel.PRIVATE)
    @Column(name = "create_date", updatable = false)
    protected LocalDateTime createDate;

    /**
     * 操作账号
     */
    @Setter(AccessLevel.PRIVATE)
    @Column(name = "create_account", updatable = false)
    protected String createAccount;

    /**
     * 最后更新时间
     */
    @Setter(AccessLevel.PRIVATE)
    @Column(name = "update_date")
    protected LocalDateTime updateDate;

    /**
     * 最后操作账号
     */
    @Setter(AccessLevel.PRIVATE)
    @Column(name = "update_account")
    protected String updateAccount;

    /**
     * 更新版本
     */
    @Setter(AccessLevel.PRIVATE)
    @Column
    protected Integer version;

    /**
     * 重新生成主键
     */
    protected void newId() {
        setFdId(IDGenerator.generateID());
    }

    /**
     * 保存或更新前回调函数，设置创建时间、最后更新时间和版本
     * <p>
     * 注意：只有数据真正发生变化时候才会执行
     */
    @PreUpdate
    @PrePersist
    private void prePersistUpdate() {
        final Token token = Token.TOKEN_LOCAL.get();
        if (getCreateDate() == null) {
            setCreateDate(LocalDateTime.now());
        }
        if (getCreateAccount() == null || getCreateAccount().isEmpty()) {
            setCreateAccount(token.getAccount());
        }

        setUpdateDate(LocalDateTime.now());
        setUpdateAccount(token.getAccount());

        Integer version = getVersion() == null ? 0 : getVersion();
        setVersion(++version);
    }
}